package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    //使用dubbo通过网络远程调用服务提供方获取数据库中的用户信息
    @Reference
    private UserService userService;

    //根据用户名查询数据库获取用户信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名查询用户
        User user = userService.findByUsername(username);
        if (user == null) {//如果用户为空
            return null;//返回null
        }
        if("1".equals(user.getStation())){
            Set<Role> roles = user.getRoles();//获取用户对应的角色
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            if (roles != null){//角色不为空遍历角色
                for (Role role : roles) {
                    authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                    Set<Permission> permissions = role.getPermissions();
                    if (permissions != null){
                        for (Permission permission : permissions) {
                            authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                        }
                    }
                }
            }
            return new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);
        } else if("0".equals(user.getStation())){
            //用户被禁用，不允许登录
            return null;
        } else {
            return null;
        }
    }
}
